package com.easybenefit.UUService.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.easybeanfit.UUService.commutill.UUDialogUtill;
import com.easybeanfit.UUService.commutill.UUJsonUtil;
import com.easybeanfit.UUService.commutill.UULogUtil;
import com.easybeanfit.UUService.commutill.UUNetUtill;
import com.easybeanfit.UUService.commutill.UUSharedUtil;
import com.easybeanfit.UUService.commutill.UUToastUtil;
import com.easybeanfit.UUService.config.UUConfig;
import com.easybeanfit.UUService.config.UUDict;
import com.easybenefit.UUService.BaseActivity;
import com.easybenefit.UUService.MyApplication;
import com.easybenefit.UUService.R;
import com.easybenefit.UUService.model.HttpCouponBean;
import com.easybenefit.UUService.model.UserInfo;
import com.easybenefit.UUService.myinterface.IActivityInterface;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.model.Information;


import org.apache.http.Header;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class SettingActivity extends BaseActivity implements IActivityInterface, View.OnClickListener {
    private TextView tv_title;//标题
    private Button btn_add;
    private Button btn_back;
    private TextView tv_name;//名称
    private TextView tv_address;//地址
    private TextView tv_contact_people;//联系人
    private TextView tv_contact_phone;//联系电话
    private TextView tv_contact_level;//等级
    private TextView tv_contact_permissions;//权限描述
    private TextView tv_join_in_time;//加盟时间
    private TextView tv_validity_time;//有效日期
    private TextView tv_distance_time;//距离时间
    private TextView tv_kefu;//客服名称
    private LinearLayout llt_kefu;
    private LinearLayout llt_online_kefu;
    private LinearLayout llt_update_password;
    private LinearLayout llt_submit_address;
    private Context context;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private UserInfo userInfo;
    private MyApplication application;
    private AMapLocationClient locationClient = null;//定位客户端
    private AMapLocationClientOption locationOption = null;//定位参数
    private final int MSG_LOCATION_START = 1;
    private final int MSG_LOCATION_FINISH = 2;
    private ProgressDialog progressDialog;
    private Dialog dialog; // 确认提示框
    private final int REQUEST_CODE_ASK_LOCATION = 1;
    private AMapLocation aMapLocationl;
    private Button btn_submit;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    this.recreate();
                } else {
                    // Permission Denied
                    Toast.makeText(context, "定位权限", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initView();
        initData();
        initListener();
    }

    @Override
    public void initData() {
        application = (MyApplication) getApplication();
        context = this;
        userInfo = ((UserInfo) UUSharedUtil.getObject(context, UUConfig.UU_USERINFO_NAME, UserInfo.class));
        if (userInfo.getIs_location().equals("0")) {//是否锁定上报地址，0未锁定，1为锁定
            llt_submit_address.setVisibility(View.GONE);
        }
        tv_title.setText(getResources().getText(R.string.setting));
        tv_name.setText(userInfo.getMer_name());
        tv_address.setText(userInfo.getMer_addr());
        tv_contact_people.setText(userInfo.getMer_contact());
        tv_contact_phone.setText(userInfo.getMer_phone());
        tv_contact_level.setText(userInfo.getMer_vip());
        tv_contact_permissions.setText(userInfo.getMer_jur());
        tv_join_in_time.setText(userInfo.getCrt_date());
        tv_validity_time.setText(userInfo.getEnd_date());
        tv_kefu.setText(userInfo.getPromname());

        long end = 0;
        try {
            end = sdf.parse(userInfo.getEnd_date()).getTime() - new Date().getTime();
            tv_distance_time.setText("距离服务有效期还有" + end / (24 * 60 * 60 * 1000) + "天");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        ;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelLocation();
    }

    @Override
    public void initView() {
        tv_title = (TextView) findViewById(R.id.top_title);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_back = (Button) findViewById(R.id.btn_back);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_contact_people = (TextView) findViewById(R.id.tv_contact_people);
        tv_contact_phone = (TextView) findViewById(R.id.tv_contact_phone);
        tv_contact_level = (TextView) findViewById(R.id.tv_contact_level);
        tv_contact_permissions = (TextView) findViewById(R.id.tv_contact_permissions);
        tv_join_in_time = (TextView) findViewById(R.id.tv_join_in_time);
        tv_validity_time = (TextView) findViewById(R.id.tv_validity_time);
        tv_distance_time = (TextView) findViewById(R.id.tv_distance_time);
        tv_kefu = (TextView) findViewById(R.id.tv_kefu);
        llt_kefu = (LinearLayout) findViewById(R.id.llt_kefu);
        llt_online_kefu = (LinearLayout) findViewById(R.id.llt_online_kefu);
        llt_update_password = (LinearLayout) findViewById(R.id.llt_update_password);
        llt_submit_address = (LinearLayout) findViewById(R.id.llt_submit_address);
    }

    @Override
    public void initListener() {
        btn_back.setOnClickListener(this);
        llt_update_password.setOnClickListener(this);
        llt_kefu.setOnClickListener(this);
        llt_online_kefu.setOnClickListener(this);
        llt_submit_address.setOnClickListener(this);
        btn_add.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_add:
                //退出登录
                application.clearActivity();
                Intent exitIntent = new Intent(context, LoginActivity.class);
                startActivity(exitIntent);
                UUSharedUtil.getDefaultSharedPreferences(context).edit().clear().commit();
                break;
            case R.id.llt_update_password:
                Intent intent = new Intent(context, UpdateActivity.class);
                startActivity(intent);
                break;
            case R.id.llt_online_kefu:
                String sysNum = UUConfig.SOBOT_SYSNUM;
                Information info = new Information();
                info.setAppKey(sysNum);
                info.setUid(userInfo.getUser_id());
                info.setPhone(userInfo.getMer_phone());
                SobotApi.startSobotChat(SettingActivity.this, info);
                break;
            case R.id.llt_kefu:
                new AlertDialog.Builder(SettingActivity.this).setTitle("系统提示")
                        .setMessage("即将拨打：" + userInfo.getPromtel()).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri
                                        .parse("tel:" + userInfo.getPromtel()));
                                startActivity(callIntent);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();

                break;
            case R.id.llt_submit_address:
                if (Build.VERSION.SDK_INT >= 23) {
                    int hasWriteContactsPermission = context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
                    if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_ASK_LOCATION);
                        return;
                    }
                }
                UUToastUtil.showToast(context, "正在进行定位请稍等！");
                showCenterDialog();
                startLocation();
                break;
        }
    }

    public void startLocation() {
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = new AMapLocationClientOption();
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        /**
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
        locationOption.setGpsFirst(true);
        // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
        locationOption.setInterval(2000);
        // 设置定位模式为高精度模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (null != aMapLocation) {
                    Message msg = mHandler.obtainMessage();
                    msg.obj = aMapLocation;
                    msg.what = MSG_LOCATION_FINISH;
                    mHandler.sendMessage(msg);
                }
            }
        });
        // 启动定位
        locationClient.startLocation();
    }

    private int count = 0;
    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                //开始定位
                case MSG_LOCATION_START:
                    count = 0;
                    break;
                // 定位完成
                case MSG_LOCATION_FINISH:
                    //UUToastUtil.showToast(context,"定位成功！");
                    aMapLocationl = (AMapLocation) msg.obj;
                    if (aMapLocationl.getErrorCode() == 0) {
                        //定位成功
                        //Toast.makeText(context, aMapLocationl.toString(), Toast.LENGTH_LONG).show();
                        btn_submit.setEnabled(true);
                        btn_submit.setText("上报地址");
                    } else {
                        //定位失败
//                        if (count%5==0)
//                        Toast.makeText(context, "定位失败", Toast.LENGTH_SHORT).show();
                    }
//                    if (count%5==0)
//                        Toast.makeText(context, aMapLocationl.toString(), Toast.LENGTH_SHORT).show();
//                    count++;
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private void initButton(View view) {
        Button cancelBtn;
        final EditText editText;
        btn_submit = (Button) view.findViewById(R.id.sure_btn);
        cancelBtn = (Button) view.findViewById(R.id.cancel_btn);
        btn_submit.setEnabled(false);
        btn_submit.setText("正在定位");
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit(aMapLocationl.getLongitude() + "," + aMapLocationl.getLatitude());
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });
    }

    private void showCenterDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_submit_location, null);
        initButton(view);
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = Gravity.CENTER;
        wl.y = Gravity.CENTER;
        wl.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240,
                getResources().getDisplayMetrics());
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                cancelLocation();
            }
        });
        dialog.show();
    }

    public void submit(String location) {
        String url = UUConfig.SERVER_BASE_URL + "updatelocation";
        String mer_id = ((UserInfo) UUSharedUtil.getObject(context, UUConfig.UU_USERINFO_NAME, UserInfo.class)).getMer_id();
        RequestParams params = new RequestParams();
        params.put("mer_id", mer_id);
        params.put("mer_location", location);
        if (!UUNetUtill.isConnected(context)) {
            UUToastUtil.showToast(context, UUDict.NOT_INTERNET);
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    progressDialog = UUDialogUtill.getLoadingBar(context, "正在操作请稍后....");
                    progressDialog.show();
                }

                @Override
                public void onFinish() {
                    progressDialog.dismiss();
                }

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String content = new String(bytes);
                    UULogUtil.e("content", content);
                    HttpCouponBean http = (HttpCouponBean) UUJsonUtil.fromJson(content, HttpCouponBean.class);
                    UUToastUtil.showToast(context, new String(http.getMessage()));
                    dialog.dismiss();
                    cancelLocation();
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }

    public void cancelLocation() {
        try {
            if (null != locationClient) {
                /**
                 * 如果AMapLocationClient是在当前Activity实例化的，
                 * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
                 */
                locationClient.onDestroy();
                locationClient = null;
                locationOption = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
